const Router = require("@koa/router");
const {Song, Singer} = require("../database/index");
const router = new Router();

//1. 添加，编辑
router.post('/add_edit', async ctx => {
  let {songId,singerId} = ctx.request.query;
  let {name, photo, lyric, url, introduce, type, } = ctx.request.body;
  const singer = await Singer.findByPk(singerId)
  if (singer) {
    if (songId) {
      //    编辑
      const song = await Song.update({
        name, photo, lyric, url, introduce, type,singerId
      }, {
        where: {
          songId
        }
      })
      // 数据库有userId返回 [1]，没有[0]
      if (song[0]) {
        ctx.body = {
          code: '200',
          msg: '修改成功',
          data: '修改成功'
        }
      } else {
        ctx.body = {
          code: '500',
          msg: '修改失败',
          data: '修改失败'
        }
      }
    } else {
      //    添加
      const song = await Song.create({
        name, photo, lyric, url, introduce, type,singerId
      })
      if (song) {
        ctx.body = {
          code: '200',
          msg: '添加成功',
          data: song
        }
      } else {
        ctx.body = {
          code: '500',
          msg: '添加失败',
          data: '添加失败'
        }
      }
    }
  } else {
    ctx.body = {
      code: '500',
      msg: '歌手不存在',
      data: '歌手不存在'
    }
  }

})

//2. 查看all/songId/singerId
router.get('/getSong', async ctx => {
  const {songId,singerId} = ctx.query;
  if (songId) {
    const song = await Song.findOne({
      where: {songId},
      include:{
        model:Singer
      }
    })
    if (song) {
      ctx.body = {
        code: '200',
        msg: '查看成功',
        data: song
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '查询失败',
        data: "查询失败"
      }
    }
  }else if(singerId){
    const song = await Song.findAll({
      where: {
        singerId
      }
    })
    if (song) {
      ctx.body = {
        code: '200',
        msg: '查看成功',
        data: song
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '查询失败',
        data: "查询失败"
      }
    }
  } else {
    const song = await Song.findAll({
      include:{
        model:Singer
      }
    });
    if (song) {
      ctx.body = {
        code: '200',
        msg: '查看成功',
        data: song
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '查询失败',
        data: "查询失败"
      }
    }
  }
})

//3. 删除some/SongId
router.get('/deleteSong', async ctx => {
  let {songId} = ctx.request.query;
  const songIds = Array.of(songId)
  if (songId.length > 0) {
    for (let songId of songIds) {
      await Song.destroy({
        where: {
          songId
        }
      })
    }
    ctx.body = {
      code: '200',
      msg: '删除成功',
      data: '删除成功'
    }
  } else {
    ctx.body = {
      code: '200',
      msg: '删除成功',
      data: '删除成功'
    }
  }
})

module.exports = router